package ve.usb.crm;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;

import ve.usb.cohesion.runtime.CohesionAction;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import ve.usb.cohesion.runtime.HibernateUtil;
import ve.usb.crm.hibernate.*;


/**
 *
 */
public class AccionesDocumento extends CohesionAction {

/**
     * Called by Struts for the execution of action ACrearDocumento.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions.
     * These exceptios will normally be treated with
     * the default exception action.
     */
    public ActionForward ACrearDocumento(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"APreOportunidad", "APreCrearDocumento", "APreProyecto"};
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;
        final int SALIDA_2 = 2;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            FCrearDocumento fFCrearDocumento = (FCrearDocumento)form;
            Documento doc = new Documento();
            String nom = fFCrearDocumento.getNombre();
            Personal per = (Personal)s.load(Personal.class, fFCrearDocumento.getPersonalCarga());
            FormFile archivo = fFCrearDocumento.getArchivo();
            boolean hayError = false;

            if (!nom.equals("")) {
                doc.setNombre(fFCrearDocumento.getNombre());
            } else {
                hayError = true;
                request.setAttribute("nombreError", "<span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>Debe colocar un nombre v&aacute;lido");
            }

            if (hayError) salida = SALIDA_1;
            else {
                DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
                doc.setFechaCarga(new Date());
                doc.setDescripcion(fFCrearDocumento.getDescripcion());
                Cuenta cuenta = new Cuenta();

                String filePath =
                   getServlet().getServletContext().getRealPath("/") +"archivosCargados";

                if (fFCrearDocumento.getIdOportunidad() != 0l) {
                    Oportunidad oportunidad = (Oportunidad)s.load(Oportunidad.class, fFCrearDocumento.getIdOportunidad());
                    cuenta = (Cuenta)oportunidad.getCuenta();
                }else if (fFCrearDocumento.getIdProyecto() != 0l) {
                    Proyecto proyecto = (Proyecto)s.load(Proyecto.class, fFCrearDocumento.getIdProyecto());
                    cuenta = (Cuenta)proyecto.getCuenta();
                }

                File folder = new File(filePath);
                if(!folder.exists()){
                    folder.mkdir();
                }

                filePath = filePath + "/" + cuenta.getNombre();

                folder = new File(filePath);
                if(!folder.exists()){
                    folder.mkdir();
                }

                String fileName = archivo.getFileName();

                if(!("").equals(fileName)){
                    System.out.println("Server path:" +filePath);
                    File newFile = new File(filePath, fileName);

                    if(!newFile.exists()){
                      FileOutputStream fos = new FileOutputStream(newFile);
                      fos.write(archivo.getFileData());
                      fos.flush();
                      fos.close();
                    }
                }

                if (fFCrearDocumento.getIdProyecto() != 0l) {
                    doc.setEsProyecto(true);
                    doc.setAsociadoA(fFCrearDocumento.getIdProyecto());
                } else {
                    doc.setEsProyecto(false);
                    doc.setAsociadoA(fFCrearDocumento.getIdOportunidad());
                }
                doc.setPersonalCarga(per);
                doc.setEnlace(filePath+"/"+fileName);
                doc.setContentType(archivo.getContentType());
                if (fFCrearDocumento.getIdDocumento() != 0l){
                    doc.setIdDocumento(fFCrearDocumento.getIdDocumento());
                    s.update(doc);
                }

                else
                    s.save(doc);
            }

            if(doc.getEsProyecto() == true){
                request.setAttribute("idProyecto", doc.getAsociadoA());
                salida = SALIDA_2;
            }
            else
                request.setAttribute("idOportunidad", doc.getAsociadoA());

            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action APreCrearDocumento.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions.
     * These exceptios will normally be treated with
     * the default exception action.
     */
    public ActionForward APreCrearDocumento(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"VCrearDocumento", };
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {

            //Trato de obtener el atributo idCuenta y obtengo el atributo usuario actual en la session
            FCrearDocumento fFCrearDocumento = FCrearDocumento.clear(mapping, request);

            if (request.getAttribute("formulario") != null)
                fFCrearDocumento = (FCrearDocumento)request.getAttribute("formulario");

            Long idOportunidad = lookup_Long(request, "idOportunidad");
            Long idProyecto = lookup_Long(request, "idProyecto");
            Personal usuario = (Personal) request.getSession().getAttribute("Usuario");

            //Verifico si vengo de una cuenta para agregarlo al formulario
            if (idProyecto != null) {
                fFCrearDocumento.setIdProyecto(idProyecto);
            }

            //Verifico si vengo de una cuenta para agregarlo al formulario
            if (idOportunidad != null) {
                fFCrearDocumento.setIdOportunidad(idOportunidad);
            }

            //Verifico si hay un usuario en la sesion para agregarlo al formulario
            if (usuario != null) {
                fFCrearDocumento.setPersonalCarga(usuario.getIdPersonal());
            }

            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action AEliminarDocumento.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions.
     * These exceptios will normally be treated with
     * the default exception action.
     */
    public ActionForward AEliminarDocumento(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"APreOportunidad", "APreProyecto"};
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            Long idDocumento = lookup_Long(request, "idDocumento");

            Documento documento = (Documento) s.load(Documento.class, idDocumento);
            if(documento.getEsProyecto() == true){
                request.setAttribute("idProyecto", documento.getAsociadoA());
                salida = SALIDA_1;
            }                
            else
                request.setAttribute("idOportunidad", documento.getAsociadoA());
            s.delete(documento);
            try {
                s.flush();
            } catch (Exception ex1) {
                ex1.printStackTrace();
                request.setAttribute("msg", "El documento no pudo ser eliminado.");
            }
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action APreModificarDocumento.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions.
     * These exceptios will normally be treated with
     * the default exception action.
     */
    public ActionForward APreModificarDocumento(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"VCrearDocumento", };
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            
            //Trato de obtener el atributo idCuenta y obtengo el atributo usuario actual en la session
            FCrearDocumento fFCrearDocumento = FCrearDocumento.clear(mapping, request);
            HttpSession sess = request.getSession();
            if (request.getAttribute("formulario") != null)
                fFCrearDocumento = (FCrearDocumento)request.getAttribute("formulario");

            Long idDocumento = lookup_Long(request, "idDocumento");
            Personal usuario = (Personal) request.getSession().getAttribute("Usuario");
            Documento doc = (Documento)s.load(Documento.class, idDocumento);
            
            //Se verifica si proviene de un proyecto para agregarlo al formulario
            if (doc.getEsProyecto() == true) {
                fFCrearDocumento.setIdProyecto(doc.getAsociadoA());
            }

            //Se verifica si proviene de una oportunidad para agregarlo al formulario
            if (doc.getEsProyecto() == false) {
                fFCrearDocumento.setIdOportunidad(doc.getAsociadoA());
            }

            //Verifico si hay un usuario en la sesion para agregarlo al formulario
            if (usuario != null) {
                fFCrearDocumento.setPersonalCarga(usuario.getIdPersonal());
            }

            fFCrearDocumento.setDescripcion(doc.getDescripcion());
            fFCrearDocumento.setNombre(doc.getNombre());
            fFCrearDocumento.setIdDocumento(idDocumento);

            sess.setAttribute("FCrearDocumento", fFCrearDocumento);
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action APreDocumentos.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions.
     * These exceptios will normally be treated with
     * the default exception action.
     */
    public ActionForward APreDocumentos(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"APreDocumento", };
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action APreDocumento.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions.
     * These exceptios will normally be treated with
     * the default exception action.
     */
    public ActionForward APreDocumento(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"APreDocumentos", };
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }



}